/*
 * Copyright (C) 2014 Snark
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package dominions.pkg4.mod.editor;

import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

/**
 *
 * @author Scalie
 */
public class UnitEditor extends javax.swing.JFrame {

    public static ArmorDatabase armors = new ArmorDatabase();
    /**
     * Creates new form UnitEditor
     */
    public UnitEditor() {
        RestoreDefaults.Restore();

        initComponents();

        updateRaceBox();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGenerator = new javax.swing.JButton();
        comboRace = new javax.swing.JComboBox();
        comboChestArmor = new javax.swing.JComboBox();
        comboLegArmor = new javax.swing.JComboBox();
        comboHelmet = new javax.swing.JComboBox();
        comboCloak = new javax.swing.JComboBox();
        comboStance = new javax.swing.JComboBox();
        unitImage = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        buttonGenerator.setText("Generate");
        buttonGenerator.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonGeneratorActionPerformed(evt);
            }
        });

        comboRace.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Abysian", "Agarthian", "Atlantian", "Caelian", "Crabman", "Foulspawn", "Hoburg", "Ichytid", "Lizard", "Tengu", "Vanir", "Machakans" }));
        comboRace.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboRaceActionPerformed(evt);
            }
        });

        comboChestArmor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Leather, 1", "Leather, 2", "Leather Hauberk, 1", "Leather Hauberk, 2", "Full Leather", "Chain Curiass", "Chain Hauberk", "Full Chain", "Scale Cuirass", "Scale Hauberk", "Scale Hauberk Long", "Full Scale", "Plate Cuirass", "Plate Hauberk", "Full Plate", "Ring Cuirass", "Ring Hauberk", "Ring Hauberk Long", "Full Ring" }));

        comboLegArmor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        comboHelmet.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        comboCloak.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        comboStance.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "standard", "2h", "bow", "crossbow", "straight" }));
        comboStance.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboStanceItemStateChanged(evt);
            }
        });
        comboStance.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboStanceActionPerformed(evt);
            }
        });

        unitImage.setBorder(new javax.swing.border.MatteBorder(null));

        javax.swing.GroupLayout unitImageLayout = new javax.swing.GroupLayout(unitImage);
        unitImage.setLayout(unitImageLayout);
        unitImageLayout.setHorizontalGroup(
            unitImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        unitImageLayout.setVerticalGroup(
            unitImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        jLabel1.setText("Race");

        jLabel2.setText("Armor");

        jLabel3.setText("Stance");

        jLabel4.setText("Leg Armor");

        jLabel5.setText("Helmet");
        jLabel5.setToolTipText("");

        jLabel6.setText("Cloak");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(comboRace, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(buttonGenerator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(unitImage, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(comboCloak, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(comboHelmet, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(comboLegArmor, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(comboChestArmor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(comboStance, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addContainerGap(162, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(comboRace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(52, 52, 52))
                    .addComponent(unitImage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonGenerator)
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboStance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboChestArmor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboLegArmor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboHelmet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboCloak, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(78, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void updateRaceBox() {
        comboRace.removeAllItems();
        String path = "graphics/races";
        File file = new File(path);
        String[] names = file.list();
        
        for(String name : names)
        {
            if(new File(path + "/" + name).isDirectory())
            {
                
                comboRace.addItem(new String(name));
            }
        }        
        updateStance();

    }
    
    private void updateArmors() {
        if(comboStance.getSelectedItem() == null)
        {
            
            
        }
        else
        {
            comboChestArmor.removeAllItems();
            String path = "armordata/" + comboStance.getSelectedItem();
            File file = new File(path);
            String[] names = file.list();

            for(String name : names)
            {
                armors.Load(path+"/" + name, "Body");      
            }
            for(Armor armor : ArmorDatabase.armorDatabase)
            {
 //               System.out.println(armor.stances + " compared to " + comboStance.getSelectedItem() + " is: " + armor.stances.equals(comboStance.getSelectedItem()));
                if(armor.stances.equals(comboStance.getSelectedItem()))
                {
                    if(armor.allowed.contains(comboRace.getSelectedItem().toString()))
                    {
                        String[] paths = armor.path.split("/");
                        comboChestArmor.addItem(paths[1]);
                    }
                }
            }
            updateLegArmors();
        }
    }
    
    private void updateStance() {
        comboStance.removeAllItems();

        String path = "graphics/races/" + comboRace.getSelectedItem();
        File file = new File(path);
        String[] names = file.list();
        
        for(String name : names)
        {
            if(new File(path + "/" + name).isDirectory())
            {
                
            }
            else
            {
                name = Functions.removeExtension(name);
                comboStance.addItem(new String(name));
            }
                   
        }       
        
    }
    
    private void updateLegArmors()
    {
        comboLegArmor.removeAllItems();
        String path = "armordata/leg";
        File file = new File(path);
        String[] names = file.list();
        String[] namesRace;
        
        for(String name :names)
        {
            if(new File(path + "/" + name).isDirectory())
            {
                if(name.equals(comboRace.getSelectedItem()))
                {
                    namesRace = new File(path+"/"+name).list();
                    for(String nameRace : namesRace)
                    {
                        System.out.println(path+"/"+comboRace.getSelectedItem()+"/"+nameRace);
                        armors.Load(path+"/"+comboRace.getSelectedItem()+"/"+nameRace, "Leg");
                    }
                }
                
            }
            else
            {
                System.out.println(path+"/"+name);
                armors.Load(path+"/"+name, "Leg");
            }
        }
        
        for(Armor armor : ArmorDatabase.legDatabase)
            {
 //               System.out.println(armor.stances + " compared to " + comboStance.getSelectedItem() + " is: " + armor.stances.equals(comboStance.getSelectedItem()));
                    if(armor.allowed.contains(comboRace.getSelectedItem().toString()))
                    {
                        String[] paths = armor.path.split("/");
                        String superpath = armor.path.substring(armor.path.lastIndexOf("/")+1);
                        comboLegArmor.addItem(superpath);
                    }
            }
        
    }
    
    private void buttonGeneratorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGeneratorActionPerformed
        // TODO add your handling code here:
//        System.out.println(comboStance.getSelectedItem().getClass());
        unitImage.removeAll();
        BufferedImage img = null;
        BufferedImage armor = null;
        BufferedImage legarmor = null;
//        System.out.println(comboChestArmor.getSelectedItem());
        try {
            img = ImageIO.read(new File("graphics/races/" + comboRace.getSelectedItem() + "/" + comboStance.getSelectedItem() + ".png"));
            armor = ImageIO.read(new File("graphics/armor/" + comboStance.getSelectedItem() + "/" + comboChestArmor.getSelectedItem()));
            legarmor = ImageIO.read(new File("graphics/armor/leg/Lizard/" + comboLegArmor.getSelectedItem()));
        } catch (IOException ex) {
            Logger.getLogger(UnitEditor.class.getName()).log(Level.SEVERE, null, ex);
        }
        int w = img.getWidth();
        int h = img.getHeight();
        
        BufferedImage combined = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
        
        Graphics g = combined.getGraphics();
        g.drawImage(img, 0, 0, null);
        g.drawImage(armor, -1 , -1 ,null);
        g.drawImage(legarmor, -1 ,-1, null);
        
        
        
        ImageIcon icon = new ImageIcon(combined, "woop");
        JLabel picLabel = new JLabel(icon);
        picLabel.setSize(combined.getHeight()*2, combined.getWidth()*2);
        unitImage.add(picLabel);
        unitImage.repaint();
        
    }//GEN-LAST:event_buttonGeneratorActionPerformed

    private void comboRaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboRaceActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comboRaceActionPerformed

    private void comboStanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboStanceActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comboStanceActionPerformed

    private void comboStanceItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboStanceItemStateChanged
        // TODO add your handling code here:
        if(evt.getStateChange() == ItemEvent.SELECTED)
        {
        updateArmors();
        }
    }//GEN-LAST:event_comboStanceItemStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UnitEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UnitEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UnitEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UnitEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UnitEditor().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonGenerator;
    private javax.swing.JComboBox comboChestArmor;
    private javax.swing.JComboBox comboCloak;
    private javax.swing.JComboBox comboHelmet;
    private javax.swing.JComboBox comboLegArmor;
    private javax.swing.JComboBox comboRace;
    private javax.swing.JComboBox comboStance;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel unitImage;
    // End of variables declaration//GEN-END:variables
}
